package com.example.ordersystem.controller;

import com.example.ordersystem.entity.Comment;
import com.example.ordersystem.entity.Order;
import com.example.ordersystem.service.CommentService;
import com.example.ordersystem.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/comments")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private OrderService orderService;

    @GetMapping("/order/{orderId}")
    public String commentPage(@PathVariable Long orderId, Model model) {
        Order order = orderService.getOrderById(orderId);
        model.addAttribute("order", order);
        List<Comment> comments = commentService.getCommentsByOrderId(orderId);
        model.addAttribute("comments", comments);
        return "comment";
    }

    @PostMapping("/add")
    public String addComment(@RequestParam Long orderId,
                             @RequestParam String content,
                             @RequestParam Integer rating) {
        Order order = orderService.getOrderById(orderId);
        if (order != null) {
            Comment comment = new Comment();
            comment.setOrder(order);
            comment.setContent(content);
            comment.setRating(rating);
            commentService.addComment(comment);
        }
        return "redirect:/comments/order/" + orderId;
    }

    @PostMapping("/reply")
    public String replyToComment(@RequestParam Long commentId,
                                 @RequestParam String reply) {
        Comment comment = commentService.replyToComment(commentId, reply);
        if (comment != null) {
            return "redirect:/comments/order/" + comment.getOrder().getId();
        }
        return "redirect:/orders";
    }
} 